package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.user.mapper.UserMapper;
import com.usian.user.service.UserService;
import com.usian.yygh.common.result.Result;
import com.usian.yygh.common.util.AppJwtUtil;
import com.usian.yygh.model.acl.User;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @Author:WGG
 * @Date 2023年01月05日 23:08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public Result addUser(User user) {
        //校验参数
        if (user==null){
            return Result.fail();
        }

//        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword() + "123456").getBytes()));
//        save(user);
        return Result.ok();

    }

    /**
     * 登录
     * @param map
     * @return
     */
    @Override
    public Result loginUser(HashMap<String, String> map) {
        //校验参数是否为空
        String username = map.get("username");
        String password = map.get("password");
        if (username==null & password==null){
            return Result.fail("请输入用户名或密码！");
        }

        //根据密码查询用户
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (user==null){
            return Result.fail("用户不存在！");
        }
        //md5加密
        password = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());
        //校验密码是否正确
        if (!password.equals(user.getPassword())){
            return Result.fail("密码错误！");
        }else {
            //携带token通过
            user.setPassword("");
            user.setSalt("");
            user.setToken(AppJwtUtil.getToken(user.getId().longValue()));
            return Result.ok(user);
        }

    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5DigestAsHex(("admin" + "123456").getBytes()));
    }

}
